package com.pascuit.gpxhandler.server.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.pascuit.gpxhandler.shared.dto.GpxInfoDto;
import com.pascuit.gpxhandler.shared.dto.UserDto;

/**
 * 
 * @author Parant
 * 
 */
public class UserDaoImpl implements UserDao {

	private PersistenceManagerFactory persistenceManagerFactory;

	@Override
	public void saveUser(UserDto user) {
		getPersistentManager().makePersistent(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserDto> getAllUsers() {
		Query query = getPersistentManager().newQuery(UserDto.class);
		return (List<UserDto>) query.execute();
	}

	@Override
	public void saveGpx(GpxInfoDto gpxInfo) {
		getPersistentManager().makePersistent(gpxInfo);
	}

	@Override
	public GpxInfoDto getByPrimaryKey(String key) {
		return getPersistentManager().getObjectById(GpxInfoDto.class, key);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserDto> fetch() {
		// test des query JDO
		Query query = getPersistentManager().newQuery(UserDto.class);
		return new ArrayList<UserDto>((List<UserDto>) query.execute());
	}

	@Override
	public void saveOrUpdate(GpxInfoDto gpxInfo) {
		UserDto user = gpxInfo.getUserDto();

		if (gpxInfo.getKey() != null) {
			GpxInfoDto persistentGpx = getPersistentManager().getObjectById(GpxInfoDto.class, gpxInfo.getKey());
			persistentGpx.setUserDto(user);
		}
	}

	public PersistenceManager getPersistentManager() {
		return this.persistenceManagerFactory.getPersistenceManager();
	}

	public PersistenceManagerFactory getPersistenceManagerFactory() {
		return persistenceManagerFactory;
	}

	public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) {
		this.persistenceManagerFactory = pmf;
	}
}
